<template>
  <div v-if='frequency == 0' class="h-screen flex justify-center items-center">
    <div>
      <p>未到课程时间，请等待!</p>
      <p>请点击历史按钮，查看以往课程记录。</p>
      <router-link :to="{ name: 'Login' }">退出并重新登录</router-link>
    </div>
  </div>

  <div v-else class="h-screen flex justify-center column">

    <template v-if="status == 2">
      <div v-if='user.classRoom == undefined' class="h-screen flex justify-center items-center">
        <p>课程尚未开始，请稍等...</p>
      </div>
      <div v-else>
        <var-card :title="`姓名：${user.name}`" :subtitle="`班级：${user.classRoom}`"
          :description="`有效期至：${timestampToTime(user.enddate)}`">
        </var-card>
        <div>
          <div>试卷准备中 </div>
        </div>
      </div>

    </template>
    <template v-else-if="status == 1">
      <div class="h-screen flex justify-center items-center">
        <div class="plist">
          <p class="m-0">您已交卷，无法进行测试！</p>
          <p class="m-0">请点击查看结果</p>
          <p class="m-0">教师讲解时将有错误提示</p>
        </div>

        <var-space>
          <var-button type="primary" class="shadow-none" @click="GOresult">查看结果</var-button>
          <var-button type="success" :loading="loadingBate" class="shadow-none" loading-type="cube" @click="getStuTest">刷题</var-button>
        </var-space>
      </div>
    </template>
    <template v-else>
      <div class="w-full h-screen">
        <div class="w-full flex justify-around items-center p-2">
          <div>
            <var-button class="shadow-none bggreen" @click="SubmitPaper">提交试卷</var-button>
          </div>
          <div>
            <var-space :size="[10, 10]">
              <var-button class="shadow-none bggreen" type="info" :disabled="num == 1"
                @click="submitAns('up')">上一题</var-button>
              <var-button class="font-bold bgGrey">第{{ num }}/{{ questions.length }}题</var-button>
              <var-button class="shadow-none bggreen" type="info" :disabled="disabledEnd"
                @click="submitAns('down')">下一题</var-button>
            </var-space>
          </div>
          <div>
            <var-countdown class="ml-auto font-bold" :time="countDowns" ref="countdown" format="HH:mm:ss" />
          </div>
        </div>
        <template v-for="(items, index ) in questions" :key="index">
          <div v-show="num == index + 1">
            <var-card class="text-left shadow-none bgGrey font-bold mt-4">
              <template #description>
                <div class="text-base px-4 py-1">
                  <span class="familyFont" v-html="items.question"></span>
                </div>
              </template>
            </var-card>
            <var-row class="p-4" :gutter="10">
              <var-col class="mb-2" :span="24">
                <var-button :class="{ primary: typeBtn == items.optionA }"
                  class="shadow-none border-gray-500 font-bold border-1 text-2xl" block
                  @click="handleSelect(items, items.optionA)">A.{{ items.optionA }}</var-button>
              </var-col>
              <var-col class="mb-2" :span="24">
                <var-button :class="{ primary: typeBtn == items.optionB }"
                  class="shadow-none border-gray-500 font-bold border-1 text-2xl" block
                  @click="handleSelect(items, items.optionB)">B. {{ items.optionB }}</var-button>
              </var-col>
              <var-col class="mb-2" :span="24">
                <var-button :class="{ primary: typeBtn == items.optionC }"
                  class="shadow-none border-gray-500 font-bold border-1 text-2xl" block
                  @click="handleSelect(items, items.optionC)">C. {{ items.optionC }}</var-button>
              </var-col>
              <var-col class="mb-2" :span="24">
                <var-button :class="{ primary: typeBtn == items.optionD }"
                  class="shadow-none border-gray-500 font-bold border-1 text-2xl" block
                  @click="handleSelect(items, items.optionD)">D. {{ items.optionD }}</var-button>
              </var-col>
            </var-row>
          </div>
        </template>
      </div>
    </template>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { postData } from '@/utils/api'
import { useRouter } from 'vue-router'
import { loginStore } from '@/store/user'
import socket from "@/utils/socket.js";
const store = loginStore();
const loadingBate = ref(false);
let user = "";
if (store.getUserInfo?.userInfo == undefined) {
  user = store.getUserInfo
} else {
  user = JSON.parse(store.getUserInfo?.userInfo)
}
const frequency = ref('')
const cusRouter = useRouter()
let questions = ref('');
let num = ref(1);
let typeBtn = ref('');
let itemData = ref('');
const status = ref(0);
let countDowns = ref(0);
const countdown = ref(null);
const disabledEnd = ref(false);
const Msgs = ref('')
let ansArrs = new Map()
const getStuTest = async () => {
  loadingBate.value = true;
  await postData('config/test/findStudentTest', { classroomId: user.classRoomId, studentId: user.id }).then(res => {
    status.value = res.data.code;
    const { data } = res.data;

    if (status.value == 1) {
      //getCode()
      Msgs.value = res.data.msg
    }
    if (status.value == 0) {
      countDowns.value = res.data.total.countdown * 1000;
      questions.value = data;
    }
    // countdown.value.start()
    frequency.value = res.data.student.frequency;
    loadingBate.value = false;
    //store.addUser(res.data.student);
  })
}



const stuAnswer = (items) => {
  postData('config/test/answer',
    {
      id: items.id,
      chooseOption: typeBtn.value,
      classroomId: items.classroomId,
      titleId: items.titleId,
      optionA: itemData.value.optionA,
      optionB: itemData.value.optionB,
      optionC: itemData.value.optionC,
      optionD: itemData.value.optionD,
    }
  ).then(res => {
    // Snackbar({
    //   content: res.data.msg,
    //   contentClass: 'p-0 text-center',
    // })
  })
}

const GOresult = () => {
  cusRouter.push("result")
}


onMounted(() => {
  // if (store.ansArrs != null) {
  //   store.ansArrs.forEach(item => {
  //     ansArrs.set(item[0], item[1])
  //   })
  //   num.value = store.ansArrs.length;
  // }
  // if (window.performance.navigation.type == 1) {
  //   console.log("页面被刷新")
  //   store.changInclassRoom(false)
  // } else {
  //   console.log("首次被加载")
  //   ansArrs.clear();
  //   num.value = 1;
  //   store.AddansArrs(ansArrs);
  //   getStuTest()
  // }

  // socket.on("connect", () => {
  //   console.log("socketio-connect");
  //   if (store.isinClassRoom == false) {
  //     socket.emit('join', Object.assign({}, {
  //       roomId: user.classRoomId,
  //       userId: user.id,
  //       userName: user.name
  //     }))
  //     store.changInclassRoom(true)
  //   }
  // });
  store.changInclassRoom(true)
  getStuTest()
})

socket.on("studentTest", (e) => {
  // ansArrs.clear();
  // num.value = 1;
  // store.AddansArrs(ansArrs);
  getStuTest()
});

const handleSelect = (items, option) => {
  typeBtn.value = option
  itemData.value = items
  ansArrs.set(num.value, { chooseOption: option, ...itemData.value });
  store.AddansArrs(ansArrs);
  stuAnswer(items)
}

const submitAns = (type) => {
  typeBtn.value = ''
  let aObj;
  if (type == 'up') {
    num.value--
    aObj = ansArrs.get(num.value);
    if (aObj == undefined) {
      typeBtn.value = '';
    } else {
      typeBtn.value = aObj.chooseOption;
    }

    disabledEnd.value = false;
  } else {
    if (num.value == questions.value.length) {
      num.value == questions.value.length;
      disabledEnd.value = true;
      aObj = ansArrs.get(num.value);
      typeBtn.value = aObj.chooseOption;
      Dialog({
        message: "太棒了！您已答完所有题! 是否提交试卷？",
        closeOnClickOverlay: false,
        onConfirm: () => SubmitPaper()
      })
      return
    }
    num.value++
    aObj = ansArrs.get(num.value);
    const qs = questions.value[num.value - 1];
    if (!aObj) {
      ansArrs.set(num.value, { chooseOption: '', ...qs });
    } else {
      typeBtn.value = aObj.chooseOption;
    }

  }

}



const SubmitPaper = () => {
  postData('config/test/studentFinish',
    {
      classroomId: user.classRoomId,
      studentId: user.id
    }
  ).then(res => {
    if (res.data.code == 0) {
      const obj = {
        teacherId: res.data.data.teacherId
      }
      socket.emit("EndTheExam", obj);
      cusRouter.push("result")
    }
  })

}
const userList = new Map()
socket.on('welcome', ({ userName, uList }) => {
  // Snackbar.success({
  //   content: "欢迎进入教室",
  //   onOpen() {
  //     store.changInclassRoom(false)
  //   }
  // })

  if (userList.size != 0) {
    userList.forEach((k, v) => {
      if (k.userName == userName) {
        userList.delete(v)
      }
    })
  }
  uList.forEach((item) => {
    const [id, value] = item;
    userList.set(id, value);
  })
  getStuTest()
})
socket.on('quit', (id) => {
  // store.changInclassRoom(true)
  // Snackbar.warning({
  //   content:"退出教室",
  //   onOpen(){
  //     if (status.value == 1) {
  //       SubmitPaper()
  //     }
  //   }
  // })
  userList.delete(id)
  //SubmitPaper()
})

socket.on('logout', (e) => {
  const { userId } = { ...e }
  if (userId === user.id) {
    store.changInclassRoom(true);
    Snackbar.warning({
      content: "退出教室",
      onOpen() {
        if (status.value == 1) {
          SubmitPaper()
        }
      }
    })
  }
})

function timestampToTime(timestamp) {
  // 时间戳为10位需*1000，时间戳为13位不需乘1000
  var date = new Date(timestamp);
  var Y = date.getFullYear() + "-";
  var M =
    (date.getMonth() + 1 < 10
      ? "0" + (date.getMonth() + 1)
      : date.getMonth() + 1) + "-";
  var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
  var h = date.getHours() + ":";
  var m = date.getMinutes() + ":";
  var s = date.getSeconds();
  return Y + M + D + h + m + s;
}

</script>

<style scoped>
.logoName {
  writing-mode: tb;
  @apply text-light-500 font-bold
}

.rightDiv {
  flex-direction: column !important;
}

:deep(.var-card__floater) {
  background: transparent !important;
}

.primary {
  color: #fff !important;
  background-color: var(--button-primary-color) !important;
}


.bggreen {
  background-color: #326a00;
  color: #fff;
  font-weight: 600;
}
.plist{
  line-height: initial;
}
</style>